import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:fluttertoast/fluttertoast.dart' as fluttertoast;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gameplay_flutter/lib_basemodel/country/country_model.dart';
import 'package:gameplay_flutter/lib_basemodel/user/user.dart';
import 'package:gameplay_flutter/lib_baseview/lib_baseview.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:gameplay_flutter/m_me/me_controller.dart';
import 'package:gameplay_flutter/m_me/user_deit_page/audio_recorder.dart';
import 'package:gameplay_flutter/m_me/user_deit_page/recording_status.dart';
import 'package:ones/ui.dart';
import '../../resource/language/generated/l10n.dart';
import '../constants/me_assets_constants.dart';
import '../model/lable_model.dart';

class UserEditPage extends StatefulWidget {
  const UserEditPage({Key? key}) : super(key: key);

  @override
  _UserEditPageState createState() => _UserEditPageState();
}

class _UserEditPageState extends State<UserEditPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool _isFocused = false;
  late final MeController meController;
  int _maxLength = 20; // 最大长度固定值
  int _currentLength = 0; // 当前长度初始为0

  String _selectedCountry = "";

  final _audioPlayer = FlutterSoundPlayer();
  RecordingStatus recordingStatus = RecordingStatus.readyToPlay;
  int seconds = 0;
  Timer? _playbackTimer;

  @override
  initState() {
    super.initState();
    meController = Get.put(MeController());
    meController.getUserDetails1();
    meController.getCountryList();
    meController.getTagList();
    // 确保 user 不为 null 再访问其属性
    _controller.text = (meController.user.value?.nickname ?? "").toString();
    setState(() {
      _currentLength = _controller.text.length;
    });
    _focusNode.addListener(_onFocusChange);
    _audioPlayer.openPlayer();
  }

  void _onFocusChange() {
    setState(() {
      _isFocused = _focusNode.hasFocus;
    });
    if (_focusNode.hasFocus) {
      print("输入框获取了焦点");
      // 可以在这里执行一些操作，比如显示辅助输入面板
    } else {
      print("输入框失去了焦点");
      // 可以在这里验证输入或隐藏键盘
    }
  }

  @override
  dispose() {
    _controller.dispose();
    _focusNode.removeListener(_onFocusChange);
    _focusNode.dispose();
    _audioPlayer.closePlayer();
    _playbackTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            Obx(() => Container(
                  height: 263.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: meController.user.value.pageImgInAudit != null &&
                              meController.user.value.pageImgInAudit!.isNotEmpty
                          ? CachedNetworkImageProvider(
                              meController.user.value.pageImgInAudit!)
                          : const AssetImage(MeAssetsConstants.iconEmpty),
                      fit: BoxFit.cover,
                    ),
                  ),
                )),
            Expanded(
                child: Container(
              color: Colors.white,
            ))
          ],
        ),
        Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              leading: IconButton(
                icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              backgroundColor: Colors.transparent,
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0x80000000), Colors.transparent], // 渐变颜色
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                ),
              ),
              actions: [
                Column(
                  children: [
                    const Spacer(),
                    Container(
                      width: 81.63.w,
                      height: 32.h,
                      padding: EdgeInsetsDirectional.only(start: 20.w),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                        image: AssetImage(
                            MeAssetsConstants.getIconChange(context)),
                        fit: BoxFit.cover,
                      )),
                      child: T.current.me1_Change.text(
                        color: Colors.white,
                        fontSize: 14.sp,
                        weight: TextFontWeight.medium,
                      ),
                    ).onClick(() {
                      meController.pickAssets(context, "pageImgInAudit").then((value){
                        _dialogToast(value);
                      });
                    }),
                  ],
                )
              ],
            ),
            body: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center, // 水平居中
                children: [
                  SizedBox(
                    height: 24.h,
                  ),
                  Stack(children: [
                    Obx(() => CircleAvatar(
                          radius: 39.r,
                          backgroundImage: meController
                                          .user.value.headPortraitsUrl !=
                                      null &&
                                  meController
                                      .user.value.headPortraitsUrl!.isNotEmpty
                              ? CachedNetworkImageProvider(
                                  meController.user.value.headPortraitsUrl!)
                              : const AssetImage(MeAssetsConstants.iconEmpty),
                        )),
                    Padding(
                      padding:
                          EdgeInsetsDirectional.only(top: 51.h, start: 48.w),
                      child: Image.asset(
                        MeAssetsConstants.iconPhoto,
                        width: 28.w,
                        height: 28.h,
                      ),
                    )
                  ]).onClick(() {
                    meController.pickAssets(context, "headPortraitsUrl").then((value){
                      _dialogToast(value);
                    });
                  }),
                  SizedBox(
                    height: 35.h,
                  ),
                  Obx(() => _basicData(meController.user.value)),
                ],
              ),
            )),
      ],
    );
  }

  Widget _basicData(User user) {
    List<String> _labelNames = user.aboutList ?? [];
    return Container(
      width: double.infinity,
      padding: EdgeInsetsDirectional.only(top: 33.h, end: 19.w, start: 25.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          T.current.m13_basic_data.text(
            color: Color(0xFF1B1B1B),
            fontSize: 20.sp,
            weight: TextFontWeight.medium,
          ),
          SizedBox(
            height: 14.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconName,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.me_edit_user_name.text(
                fontSize: 16.sp,
                color: const Color(0xFF1B1B1B),
                weight: TextFontWeight.regular),
          ]),
          // _buildFormName(user),
          SizedBox(
            height: 10.h,
          ),
          Row(
            children: [
              (user.nickname ?? "").text(
                  fontSize: 18.sp,
                  color: const Color(0xFFA8A8A8),
                  weight: TextFontWeight.regular),
              const Spacer(),
              Image.asset(
                MeAssetsConstants.getIconEditUserArrow(context),
                width: 20.sp,
                height: 20.sp,
                color: Color(0xFF1B1B1B),
              ),
            ],
          ).onClick(() {
            _showNameDialog(context, user.nickname ?? "");
          }),
          SizedBox(
            height: 10.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
          SizedBox(
            height: 7.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconBirth,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.m13_date_of_birth.text(
              color: Color(0xFF1B1B1B),
              fontSize: 16.sp,
              weight: TextFontWeight.regular,
            ),
          ]),
          SizedBox(
            height: 10.h,
          ),
          (user.birth ?? "26-01-1999").text(
            fontSize: 18.sp,
            weight: TextFontWeight.regular,
            color: const Color(0xFFA8A8A8),
          ),
          SizedBox(
            height: 8.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
          SizedBox(
            height: 7.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconCountry,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.h1_countries.text(
              color: Color(0xFF1B1B1B),
              fontSize: 16.sp,
              weight: TextFontWeight.regular,
            ),
          ]),
          SizedBox(
            height: 10.h,
          ),
          Row(
            children: [
              (user.country ?? "Select Country").text(
                  fontSize: 18.sp,
                  color: const Color(0xFFA8A8A8),
                  weight: TextFontWeight.regular),
              const Spacer(),
              Image.asset(
                MeAssetsConstants.getIconEditUserArrow(context),
                width: 20.sp,
                height: 20.sp,
                color: Color(0xFF1B1B1B),
              ),
            ],
          ).onClick(() {
            _showCoutryDialog(context, meController.countryList.value,
                meController.user.value.country ?? "");
          }),
          SizedBox(
            height: 10.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
          SizedBox(
            height: 10.h,
          ),
          T.current.m13_about_me.text(
            color: const Color(0xFF1B1B1B),
            fontSize: 20.sp,
            weight: TextFontWeight.medium,
          ),
          SizedBox(
            height: 14.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconTag,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.m13_tag.text(
              color: Color(0xFF1B1B1B),
              fontSize: 16.sp,
              weight: TextFontWeight.regular,
            ),
          ]),
          SizedBox(
            height: 10.h,
          ),
          Row(
            children: [
              if (user.aboutList != null && user.aboutList!.isNotEmpty)
                Expanded(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: _labelNames.map((tag) {
                        return Row(
                          children: [
                            SizedBox(
                              width: 4.w,
                            ),
                            _tagItem0(tag),
                          ],
                        );
                      }).toList(),
                    ),
                  ),
                )
              else
                Expanded(
                  child: "Select Tags".text(
                      fontSize: 18.sp,
                      weight: TextFontWeight.regular,
                      color: const Color(0xFFA8A8A8)),
                ),
              Image.asset(
                MeAssetsConstants.getIconEditUserArrow(context),
                width: 20.sp,
                height: 20.sp,
                color: Color(0xFF1B1B1B),
              ),
            ],
          ).onClick(() {
            _showTagsDialog(context, meController.tagList, _labelNames);
          }),
          SizedBox(
            height: 10.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
          SizedBox(
            height: 10.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconBio,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.me_edit_bio.text(
              color: const Color(0xFF1B1B1B),
              fontSize: 16.sp,
              weight: TextFontWeight.regular,
            ),
          ]),
          SizedBox(
            height: 10.h,
          ),
          Row(
            children: [
              ((user.about == null || user.about!.isEmpty)
                      ? "Add Bio"
                      : user.about!)
                  .text(
                color: const Color(0xFFA8A8A8),
                weight: TextFontWeight.regular,
                fontSize: 18.sp,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
              const Spacer(),
              Image.asset(
                MeAssetsConstants.getIconEditUserArrow(context),
                width: 20.sp,
                height: 20.sp,
                color: Color(0xFF1B1B1B),
              ),
            ],
          ).onClick(() {
            _showBioDialog(context, meController.user.value.about ?? "");
          }),
          SizedBox(
            height: 10.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
          SizedBox(
            height: 10.h,
          ),
          Row(children: [
            Image.asset(
              MeAssetsConstants.iconVoice,
              width: 20.w,
              height: 20.h,
            ),
            SizedBox(
              width: 4.w,
            ),
            T.current.m13_my_voice.text(
              color: const Color(0xFF1B1B1B),
              fontSize: 16.sp,
              weight: TextFontWeight.regular,
            ),
          ]),
          SizedBox(
            height: 10.h,
          ),
          if (user.myVoice != null && user.myVoice!.isNotEmpty)
            _myVoice(user)
          else
            Row(
              children: [
                T.current.m13_record_sound.text(
                  color: Color(0xFFA8A8A8),
                  fontSize: 18.sp,
                  weight: TextFontWeight.regular,
                ),
                const Spacer(),
                Image.asset(
                  MeAssetsConstants.getIconEditUserArrow(context),
                  width: 20.sp,
                  height: 20.sp,
                  color: Color(0xFF1B1B1B),
                ),
              ],
            ).onClick(() {
              _showRecordDialog();
            }),
          SizedBox(
            height: 10.h,
          ),
          Divider(
            height: 0,
            thickness: 0.5.h,
            color: Color(0xFFEAEAEA),
          ),
        ],
      ),
    );
  }

  Widget _buildFormName(User user) {
    return Row(
      children: [
        Expanded(
          child: Form(
            child: SizedBox(
              height: 35.h,
              child: TextFormField(
                focusNode: _focusNode,
                controller: _controller,
                style: TextStyle(
                    fontSize: 18.sp,
                    color: _isFocused ? Color(0xFF1B1B1B) : Color(0xFFA8A8A8)),
                textInputAction: TextInputAction.done,
                decoration: InputDecoration(
                  hintStyle:
                      TextStyle(fontSize: 18.sp, color: Color(0xFFA8A8A8)),
                  hintText: 'Enter your name',
                  border: InputBorder.none,
                  counterText: '',
                ),
                maxLength: 20,
                maxLines: 1,
                onChanged: (value) {
                  setState(() {
                    _currentLength = value.length;
                  });
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
              ),
            ),
          ),
        ),
        if (_isFocused)
          Row(
            children: [
              Padding(
                padding: EdgeInsetsDirectional.only(top: 2.w),
                child: Text("$_currentLength/$_maxLength",
                    style:
                        TextStyle(fontSize: 12.sp, color: Color(0xFFA8A8A8))),
              ),
              Image.asset(
                MeAssetsConstants.iconClean,
                width: 16.w,
                height: 16.h,
              )
            ],
          )
      ],
    );
  }

  _showCoutryDialog(
      BuildContext context, List<CountryModel> countryList, String country) {
    _selectedCountry = country;
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.white,
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              bool isSelected =
                  _selectedCountry.isNotEmpty && country != _selectedCountry;
              return Container(
                height: MediaQuery.of(context).size.height * 0.85,
                child: Column(children: [
                  SizedBox(height: 15.h),
                  Stack(
                    children: [
                      Center(
                          child: T.current.login_edit_select_country.text(
                        color: const Color(0xFF1B1B1B),
                        fontSize: 18.sp,
                        weight: TextFontWeight.regular,
                      )),
                      Padding(
                        padding:
                            EdgeInsetsDirectional.only(start: 13.w, top: 5.h),
                        child: Icon(Icons.close,
                            color: Color(0xFF272636), size: 22.sp),
                      ).onClick(() {
                        Navigator.pop(context);
                      })
                    ],
                  ),
                  SizedBox(height: 5.h),
                  Expanded(
                      child: ListView.builder(
                          itemCount: countryList.length,
                          itemBuilder: (context, index) {
                            final flagUrl =
                                countryList[index].flag ?? ''; // 提供默认值以避免 null
                            final countryName =
                                countryList[index].country ?? '';
                            final isCountrySelected =
                                countryName == _selectedCountry;
                            return InkWell(
                              onTap: () {
                                setState(() {
                                  _selectedCountry = countryName;
                                });
                              },
                              child: Container(
                                  margin: EdgeInsetsDirectional.symmetric(
                                      horizontal: 15.w, vertical: 7.5.h),
                                  padding:
                                      EdgeInsetsDirectional.only(start: 12.w),
                                  height: 32.h,
                                  decoration: BoxDecoration(
                                      color: Color(isCountrySelected
                                          ? 0xFFE5DFFF
                                          : 0xFFF4F3F6),
                                      borderRadius: BorderRadius.circular(4.r)),
                                  child: Padding(
                                    padding: EdgeInsetsDirectional.only(
                                        start: 12.w, end: 17.w),
                                    child: Row(children: [
                                      if (flagUrl.isNotEmpty) // 检查图片 URL 是否有效
                                        Image.network(
                                          flagUrl, // 使用非空的 flagUrl
                                          width: 26.w,
                                          height: 18.h,
                                        ),
                                      SizedBox(
                                        width: 8.w,
                                      ),
                                      Text(countryName),
                                      Spacer(),
                                      if (isCountrySelected)
                                        Image.asset(
                                          MeAssetsConstants.iconCountrySelected,
                                          color: Color(0xFF8A72FE),
                                          width: 24.w,
                                          height: 24.h,
                                        ),
                                    ]),
                                  )),
                            );
                          })),
                  Container(
                    alignment: Alignment.center,
                    color: Colors.white,
                    width: MediaQuery.of(context).size.width,
                    height: 122.h,
                    child: Opacity(
                      opacity: isSelected ? 1.0 : 0.3,
                      child: Container(
                        alignment: Alignment.center,
                        width: 248.w,
                        height: 44.h,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [
                              Color(0xFF8A72FE),
                              Color(0xFF6549EC)
                            ], // 渐变色数组
                            begin: Alignment.topLeft, // 渐变起始位置
                            end: Alignment.bottomRight, // 渐变结束位置
                          ),
                          borderRadius: BorderRadius.circular(35.r),
                        ),
                        child: T.current.login_edit_sure.text(
                          color: Colors.white,
                          fontSize: 20.sp,
                          weight: TextFontWeight.regular,
                        ),
                      ).onClick(() {
                        if (isSelected) {
                          meController
                              .uploadUser("country", _selectedCountry)
                              .then((value) {
                            Navigator.pop(context);
                            _dialogToast(value);
                          });
                        }
                      }),
                    ),
                  ),
                ]),
              );
            },
          );
        });
  }

  _showNameDialog(BuildContext context, String name) {
    final TextEditingController _nameController = TextEditingController();
    final _focusNode = FocusNode();
    var _nameLength = name.length;
    var _newName = name;
    _nameController.text = _newName;
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              bool _isNameNotChanged = _newName == name || _newName.isEmpty;
              return AnimatedPadding(
                padding: EdgeInsetsDirectional.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom, // 根据键盘高度调整
                ),
                duration: const Duration(milliseconds: 150),
                child: SizedBox(
                  height: 333.h,
                  child: Column(children: [
                    SizedBox(height: 15.h),
                    Stack(
                      children: [
                        Center(
                            child: T.current.me_edit_change_name.text(
                          color: const Color(0xFF1B1B1B),
                          fontSize: 20.sp,
                          weight: TextFontWeight.medium,
                        )),
                        Padding(
                          padding:
                              EdgeInsetsDirectional.only(start: 23.w, top: 2.h),
                          child: T.current.me_edit_cancel.text(
                            fontSize: 18.sp,
                            color: const Color(0xFFA8A8A8),
                            weight: TextFontWeight.regular,
                          ),
                        ).onClick(() {
                          Navigator.pop(context);
                        })
                      ],
                    ),
                    Container(
                      margin: EdgeInsetsDirectional.symmetric(
                          horizontal: 15.w, vertical: 16.h),
                      padding:
                          EdgeInsetsDirectional.only(start: 13.w, end: 13.w),
                      height: 42.h,
                      decoration: BoxDecoration(
                          color: const Color(0xFFFAFAFA),
                          borderRadius: BorderRadius.circular(8.r)),
                      child: Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              controller: _nameController,
                              focusNode: _focusNode,
                              keyboardType: TextInputType.multiline,
                              style: TextStyle(
                                  fontSize: 14.sp, color: Color(0xFF1B1B1B)),
                              decoration: InputDecoration(
                                hintStyle: TextStyle(
                                    fontSize: 14.sp, color: Color(0xFFC1C1C1)),
                                hintText: T.current.me_edit_input_nickname,
                                border: InputBorder.none,
                                counterText: "",
                              ),
                              maxLength: 20,
                              maxLines: null,
                              onChanged: (value) {
                                setState(() {
                                  // 更新当前长度
                                  _nameLength = value.length;
                                  _newName = value;
                                });
                              },
                            ),
                          ),
                          Text(
                            "$_nameLength/20",
                            style: TextStyle(
                                fontSize: 12.sp,
                                color: Color(0xFFC1C1C1),
                                fontWeight: FontWeight.normal),
                          ),
                          SizedBox(width: 5.w),
                          Image.asset(
                            MeAssetsConstants.iconClean,
                            width: 16.w,
                            height: 16.h,
                          ).onClick(() {
                            setState(() {
                              _nameController.clear();
                              _newName = "";
                              _nameLength = 0;
                            });
                          })
                        ],
                      ),
                    ),
                    const Spacer(),
                    Center(
                      child: Opacity(
                        opacity: _isNameNotChanged ? 0.3 : 1,
                        child: Container(
                          alignment: Alignment.center,
                          width: 248.w,
                          height: 44.h,
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              colors: [
                                Color(0xFF8A72FE),
                                Color(0xFF6549EC)
                              ], // 渐变色数组
                              begin: Alignment.topLeft, // 渐变起始位置
                              end: Alignment.bottomRight, // 渐变结束位置
                            ),
                            borderRadius: BorderRadius.circular(35.r),
                          ),
                          child: T.current.me_edit_save.text(
                            fontSize: 20.sp,
                            color: Colors.white,
                            weight: TextFontWeight.medium,
                          ),
                        ).onClick(() {
                          if (!_isNameNotChanged) {
                            meController
                                .uploadUser("nickname", _newName)
                                .then((value) {
                              Navigator.pop(context);
                              _dialogToast(value);
                            });
                          }
                        }),
                      ),
                    ),
                    SizedBox(height: 20.h),
                  ]),
                ),
              );
            },
          );
        });
  }

  _showBioDialog(BuildContext context, String bio) {
    final _focusNode = FocusNode();
    var _bioLength = bio.length;
    var _newBio = bio;

    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              bool _isBioNotChanged = _newBio == bio || _newBio.isEmpty;
              return AnimatedPadding(
                padding: EdgeInsetsDirectional.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom, // 根据键盘高度调整
                ),
                duration: const Duration(milliseconds: 150),
                child: SizedBox(
                  height: 333.h,
                  child: Column(children: [
                    SizedBox(height: 15.h),
                    Stack(
                      children: [
                        Center(
                          child: T.current.m13_add_bio.text(
                              color: const Color(0xFF1B1B1B),
                              fontSize: 22.sp,
                              weight: TextFontWeight.medium),
                        ),
                        Padding(
                          padding:
                              EdgeInsetsDirectional.only(start: 23.w, top: 2.h),
                          child: T.current.me_edit_cancel.text(
                            fontSize: 18.sp,
                            color: const Color(0xFFA8A8A8),
                            weight: TextFontWeight.regular,
                          ),
                        ).onClick(() {
                          Navigator.pop(context);
                        })
                      ],
                    ),
                    Container(
                      margin: EdgeInsetsDirectional.symmetric(
                          horizontal: 15.w, vertical: 16.h),
                      padding: EdgeInsetsDirectional.only(
                          start: 13.w, end: 13.w, bottom: 12.h),
                      height: 160.h,
                      decoration: BoxDecoration(
                          color: const Color(0xFFFAFAFA),
                          borderRadius: BorderRadius.circular(8.r)),
                      child: Column(
                        children: [
                          Expanded(
                            child: TextFormField(
                              focusNode: _focusNode,
                              keyboardType: TextInputType.multiline,
                              style: TextStyle(
                                  fontSize: 14.sp, color: Color(0xFF1B1B1B)),
                              decoration: InputDecoration(
                                hintStyle: TextStyle(
                                    fontSize: 14.sp, color: Color(0xFFC1C1C1)),
                                hintText: T.current.me_edit_about,
                                border: InputBorder.none,
                                counterText: "",
                              ),
                              initialValue: bio ?? "",
                              maxLength: 100,
                              maxLines: null,
                              onChanged: (value) {
                                setState(() {
                                  // 更新当前长度
                                  _bioLength = value.length;
                                  _newBio = value;
                                });
                              },
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerRight,
                            child: Text(
                              "$_bioLength/100",
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Color(0xFFC1C1C1),
                                  fontWeight: FontWeight.normal),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 15.h),
                    Center(
                      child: Opacity(
                        opacity: _isBioNotChanged ? 0.5 : 1.0,
                        child: Container(
                          alignment: Alignment.center,
                          width: 248.w,
                          height: 44.h,
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              colors: [
                                Color(0xFF8A72FE),
                                Color(0xFF6549EC)
                              ], // 渐变色数组
                              begin: Alignment.topLeft, // 渐变起始位置
                              end: Alignment.bottomRight, // 渐变结束位置
                            ),
                            borderRadius: BorderRadius.circular(35.r),
                          ),
                          child: T.current.me_edit_save.text(
                            fontSize: 20.sp,
                            color: Colors.white,
                            weight: TextFontWeight.medium,
                          ),
                        ).onClick(() {
                          if (!_isBioNotChanged) {
                            meController
                                .uploadUser("about", _newBio)
                                .then((value) {
                              Navigator.pop(context);
                              _dialogToast(value);
                            });
                          }
                        }),
                      ),
                    ),
                  ]),
                ),
              );
            },
          );
        });
  }

  bool compareTags(List<String> oldTags, List<String> newTags) {
    return oldTags.toSet().difference(newTags.toSet()).isEmpty &&
        newTags.toSet().difference(oldTags.toSet()).isEmpty;
  }

  _showTagsDialog(BuildContext context, List<LableModel> tagsModelList,
      List<String> aboutList) {
    List<String> _oldTags = aboutList;
    var userLabelItemsSet = getAllUserLabelItems(tagsModelList);
    var _olds = filterUserLabelItems(userLabelItemsSet, _oldTags);
    List<UserLabelItems> _news = List.from(_olds);
    bool _isTagsNotChanged = true; // 标记标签是否未改变
    int _meTags = _news.length; // 当前选中的标签数量
    // var tags = mergeUserLabels(tagsModelList);
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        constraints: BoxConstraints.loose(
            Size.fromHeight(MediaQuery.of(context).size.height)),
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return ConstrainedBox(
                constraints: BoxConstraints(
                  minHeight: 370.h, // 设置最小高度
                  maxHeight: MediaQuery.of(context).size.height,
                ),
                child: Container(
                  child: Column(mainAxisSize: MainAxisSize.min, children: [
                    SizedBox(height: 25.h),
                    Stack(
                      children: [
                        Center(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              T.current.me_edit_selected_tag.text(
                                fontSize: 20.sp,
                                color: const Color(0xFF1B1B1B),
                                weight: TextFontWeight.medium,
                              ),
                              "($_meTags/4)".text(
                                fontSize: 20.sp,
                                color: const Color(0xFF1B1B1B),
                                weight: TextFontWeight.medium,
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding:
                              EdgeInsetsDirectional.only(start: 23.w, top: 2.h),
                          child: T.current.me_edit_cancel.text(
                            fontSize: 16.sp,
                            color: const Color(0xFFA8A8A8),
                            weight: TextFontWeight.regular,
                          ),
                        ).onClick(() {
                          Navigator.pop(context);
                        })
                      ],
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      padding: EdgeInsetsDirectional.only(
                          start: 17.w, top: 30.h, end: 10.w, bottom: 15.h),
                      child: Wrap(
                        spacing: 10.w,
                        runSpacing: 16.h,
                        children: userLabelItemsSet.map((lableItem) {
                          return _tagItem(
                            _news,
                            lableItem.labelName ?? "",
                          ).onClick(() {
                            setState(() {
                              if (containsLabel(
                                  _news, lableItem.labelName ?? "")) {
                                removeLabel(_news, lableItem.labelName ?? "");
                                _meTags--;
                                _isTagsNotChanged =
                                    compareLabelNames(_olds, _news);
                              } else {
                                if (_meTags < 4) {
                                  _news.add(lableItem);
                                  _meTags++;
                                  _isTagsNotChanged =
                                      compareLabelNames(_olds, _news);
                                } else {
                                  fluttertoast.Fluttertoast.cancel();
                                  fluttertoast.Fluttertoast.showToast(
                                    msg: T.current.me_edit_only4,
                                    toastLength:
                                        fluttertoast.Toast.LENGTH_SHORT,
                                    // 显示时长 (SHORT 或 LONG)
                                    gravity: fluttertoast.ToastGravity.CENTER,
                                    // 让 Toast 显示在屏幕中央
                                    backgroundColor: Colors.black54,
                                    textColor: Colors.white,
                                  );
                                }
                              }
                            });
                          });
                        }).toList(),
                      ),
                    ),
                    SizedBox(height: 15.h),
                    Opacity(
                      opacity: _isTagsNotChanged ? 0.5 : 1.0,
                      child: Container(
                        alignment: Alignment.center,
                        width: 248.w,
                        height: 44.h,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [
                              Color(0xFF8A72FE),
                              Color(0xFF6549EC)
                            ], // 渐变色数组
                            begin: Alignment.topLeft, // 渐变起始位置
                            end: Alignment.bottomRight, // 渐变结束位置
                          ),
                          borderRadius: BorderRadius.circular(35.r),
                        ),
                        child: T.current.me_edit_save.text(
                          fontSize: 20.sp,
                          color: Colors.white,
                          weight: TextFontWeight.medium,
                        ),
                      ).onClick(() {
                        if (!_isTagsNotChanged) {
                          String labelsString = _news
                              .map((item) => item.label)
                              .whereType<String>()
                              .join(' ');
                          meController
                              .uploadUser("interests", labelsString)
                              .then((value) {
                            _dialogToast(value);
                            Navigator.pop(context);
                          });
                        }
                      }),
                    ),
                  ]),
                ),
              );
            },
          );
        });
  }

  Widget _tagItem(List<UserLabelItems> labels, String label) {
    var _isTagSelected = containsLabel(labels, label);
    return Container(
      decoration: BoxDecoration(
        color: Color(_isTagSelected ? 0xFFFFFFFF : 0xFFF8F6FF),
        borderRadius: BorderRadius.circular(36.r),
        border: _isTagSelected
            ? Border.all(
                color: Color(
                  0xFF8A72FE,
                ),
                width: 1.w,
                style: BorderStyle.solid,
              )
            : Border.all(
                color: Colors.white,
                width: 1.w,
                style: BorderStyle.solid,
              ),
      ),
      child: Padding(
        padding:
            EdgeInsetsDirectional.symmetric(horizontal: 15.w, vertical: 3.5.h),
        child: Text(label,
            style: TextStyle(
                fontSize: 14.sp,
                color: Color(_isTagSelected ? 0xFF8A72FE : 0xFFCBB1DF),
                fontWeight: FontWeight.normal)),
      ),
    );
  }

  Widget _tagItem0(String label) {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFFFFFFFF),
        borderRadius: BorderRadius.circular(36.r),
        border: Border.all(
          color: Color(
            0xFF8A72FE,
          ),
          width: 1.w,
          style: BorderStyle.solid,
        ),
      ),
      child: Padding(
        padding:
            EdgeInsetsDirectional.symmetric(horizontal: 15.w, vertical: 3.5.h),
        child: Text(label,
            style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF8A72FE),
                fontWeight: FontWeight.normal)),
      ),
    );
  }

  List<UserLabelItems> getAllUserLabelItems(List<LableModel> lableModels) {
    List<UserLabelItems> userLabelItemsSet = [];

    for (var lableModel in lableModels) {
      if (lableModel.userLabelItems != null) {
        userLabelItemsSet.addAll(lableModel.userLabelItems!);
      }
    }

    return userLabelItemsSet;
  }

  List<UserLabelItems> filterUserLabelItems(
      List<UserLabelItems> userLabelItemsSet, List<String> oldTags) {
    List<UserLabelItems> filteredSet = [];

    for (var userLabelItem in userLabelItemsSet) {
      if (oldTags.contains(userLabelItem.labelName)) {
        filteredSet.add(userLabelItem);
      }
    }

    return filteredSet;
  }

  bool containsLabel(List<UserLabelItems> labels, String label) {
    return labels.any((userLabelItem) => userLabelItem.labelName == label);
  }

  void removeLabel(List<UserLabelItems> labels, String label) {
    labels.removeWhere((userLabelItem) => userLabelItem.labelName == label);
  }

  bool compareLabelNames(List<UserLabelItems> olds, List<UserLabelItems> news) {
    // 标准化标签名称：去除不可见字符并转换为小写
    List<String> oldLabels = olds
        .map((item) =>
            item.labelName
                ?.replaceAll(RegExp(r'[^\w\s]'), '')
                ?.toLowerCase()
                ?.trim() ??
            "")
        .toList()
      ..sort();
    List<String> newLabels = news
        .map((item) =>
            item.labelName
                ?.replaceAll(RegExp(r'[^\w\s]'), '')
                ?.toLowerCase()
                ?.trim() ??
            "")
        .toList()
      ..sort();

    debugPrint("Standardized oldLabels: $oldLabels, newLabels: $newLabels");
    debugPrint("Are labels equal? ${oldLabels == newLabels}");

    // 使用 Set 对称差集方法进一步验证
    Set<String> oldSet = Set.from(oldLabels);
    Set<String> newSet = Set.from(newLabels);

    bool isEqual =
        oldSet.difference(newSet).isEmpty && newSet.difference(oldSet).isEmpty;

    debugPrint("Set comparison result: $isEqual");

    return isEqual;
  }

  _showRecordDialog() {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (context) {
          return const AudioRecorder();
        });
  }

  _dialogToast(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Color(0x80000000),
        textColor: Colors.white,
        fontSize: 16.0);
  }

  _myVoice(User user) {
    return Container(
        width: 127.w,
        height: 26.h,
        decoration: BoxDecoration(
          color: const Color(0xFFFAFAFA),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Row(
          children: [
            SizedBox(
              width: 7.w,
            ),
            Image.asset(
              MeAssetsConstants.iconVoicePlay,
              width: 22.w,
              height: 22.h,
            ),
            Spacer(),
            Text(
              "${seconds == 0 ? user.duration : seconds}s",
              style: TextStyle(fontSize: 14.sp, color: Color(0xFFA8A8A8)),
            ),
            VerticalDivider(
              color: Color(0xFFE4E4E4),
              thickness: 0.6.w,
              indent: 3.h,
              endIndent: 3.h,
            ),
            Image.asset(
              MeAssetsConstants.iconVoiceClean,
              width: 22.w,
              height: 22.h,
            ).onClick(() {
              meController.deleteVoice().then((vuale) {
                _dialogToast("Successfully updated");
              });
            }),
            SizedBox(width: 7.w),
          ],
        )).onClick(() {
      if (recordingStatus == RecordingStatus.readyToPlay) {
        playRecording();
      } else if (recordingStatus == RecordingStatus.playing) {
        pauseRecording();
      }
    });
  }

  void playRecording() async {
    setState(() {
      recordingStatus = RecordingStatus.playing;
      seconds = meController.user.value.duration ?? 0;
    });
    var voicePath = meController.user.value.myVoice;
    if (voicePath != null) {
      await _audioPlayer.startPlayer(
        fromURI: voicePath,
        codec: Codec.aacADTS,
        whenFinished: () {
          setState(() {
            recordingStatus = RecordingStatus.readyToPlay;
            _playbackTimer?.cancel();
            seconds = meController.user.value.duration ?? 0;
          });
        },
      );
      _playbackTimer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          seconds--;
        });
      });
    }
  }

  void pauseRecording() async {
    setState(() {
      recordingStatus = RecordingStatus.readyToPlay;
      _playbackTimer?.cancel();
      seconds = 0;
    });
    await _audioPlayer.stopPlayer();
  }
}
